from .relys import BitSet
from .relys import Chip

class Counter(Chip):
    def __init__(self, width):
        super().__init__(width*2+5, [0, width+5], [width+5, width*2+5])
        self.RST = self.pinIN@[0]
        self.CLK = self.pinIN@[1]
        self.EI = self.pinIN@[2]
        self.EO = self.pinIN@[3]
        self.EN = self.pinIN@[4]
        self.DAT = self.pinIN@[5, width+5]
        self._dat = BitSet(width)

@Counter.keyframe(0)
def _frame(chip):
    if chip.RST() : 
        chip._dat(0)
        chip.pinOUT(0)
        return None
    elif chip.CLK() & chip.EN() : 
        chip._dat(chip._dat() + 1)
    return chip

@Counter.keyframe(1)
def _frame(chip):
    if chip.EO() : chip.pinOUT(chip._dat())
    else : chip.pinOUT(0)
    return chip

@Counter.keyframe(2)
def _frame(chip):
    if chip.CLK() & chip.EI() : chip._dat(chip.DAT())
    return None

if __name__ == "__main__":
    c = Counter(4)
    c.CLK(1)
    c.EN(1)
    c.EO(1)
    for j in range(4):
        for i in range(Counter.maxframe+1):
            c.update(i)
            print(f"<frame>:[{j*3+i}]", c)

